#include <iostream>
#include <string>
#include <string.h>
#include <strings.h>
using namespace std;
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>

void Usage(char *proc)
{
    cout << "Usage:\n\t" << proc << "  server_ip  server_port\n"
         << endl;
}

// server_ip server_port
int main(int argc, char *argv[])
{
    if (argc != 3)
    {
        Usage(argv[0]);
        exit(1);
    }
    int sockfd = socket(AF_INET, SOCK_DGRAM, 0);
    if (sockfd < 0)
    {
        cout << "socket error" << endl;
        exit(2);
    }

    string server_ip = argv[1];
    uint16_t server_port = stoi(argv[2]);

    struct sockaddr_in server;
    bzero(&server, sizeof(server));
    server.sin_family = AF_INET;
    server.sin_addr.s_addr = inet_addr(server_ip.c_str());
    server.sin_port = htons(server_port);
    string message;

    while (true)
    {

        // 1. 向传入的固定 套接字 ip port 发消息
        cout << "Please Enter# ";
        getline(cin, message);
        ssize_t n = sendto(sockfd, message.c_str(), message.size(), 0, (struct sockaddr *)&server, sizeof(server));
        if (n < 0)
        {
            cout << "sendto error" << endl;
            exit(3);
        }

        // 2. 接收来自不同 ip 的消息
        struct sockaddr_in peer;
        memset(&peer, 0, sizeof(peer));
        socklen_t len = sizeof(peer);
        char buffer[1024];
        n = recvfrom(sockfd, buffer, sizeof(buffer), 0, (struct sockaddr *)&peer, &len);
        buffer[n] = 0;// 手动添加 '\0'
        if (n > 0)
        {
            cout << "server echo# " << buffer << endl;
        }
        else if (n < 0)
        {
            cout << "recvfrom error" << endl;
            exit(4);
        }
    }

    return 0;
}